const nameInp = document.querySelector('.nickname')
const age = document.querySelector('.age')
const gender = document.querySelector('.gender')
const form  = document.querySelector('form')
const identity = document.querySelector('.identity')

const id = window.localStorage.getItem('id')
const token = window.localStorage.getItem('token')


//没有登录自动跳转登录页
testLogin()
function testLogin(){
    if(!id || !token){
        return window.location.href = './login.html'
    }
    getInfo()
}

//获取个人信息
function getInfo(){
    ajax({
        url:'http://localhost:8888/users/info',
        metode:'get',
        data:'id='+id,
        headers:{authorization:token},
        dataType:'json',
        success(res){
            if(res.code !== 1){
                window.location.href = './login.html'
                return
            }
            nameInp.value = res.info.nickname
            age.value = res.info.age
            gender.value = res.info.gender
            identity.value = res.info.identity
        }
    })
}


//修改个人信息
form.addEventListener('submit',e=>{
    e = e || window.event
    try{e.preventDefault()}catch(err){e.returnValue = false}

    const info = {
        id
    }
    if(age.value) info.age = age.value
    if(gender.value) info.gender = gender.value
    if(identity.value) info.identity = identity.value
    if(nameInp.value) info.nickname = nameInp.value 

    ajax({
        url:'http://localhost:8888/users/update',
        data:querystringify(info),
        method:'post',
        headers:{authorization:token},
        dataType:'json',
        success(){
            layer.msg('修改用户信息成功');
        }
    })
})